import {messages} from "share/common";
/**
 *  createc by jsq on 2017/9/19
 */
import React from 'react';
import { Button, Form, Select,Input, Col, Row, Switch, message, Icon} from 'antd';
import { connect } from 'react-redux'
import budgetService from 'containers/budget-setting/budget-organization/budget-structure/budget-structure.service'
import 'styles/budget-setting/budget-organization/budget-structure/new-budget-structure.scss';
import menuRoute from 'routes/menuRoute'
import debounce from 'lodash.debounce';
import { LanguageInput } from 'components/template';

const FormItem = Form.Item;
const Option = Select.Option;

class NewBudgetStructure extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      loading: false,
      statusCode: messages('common.enabled'),  /*启用*/
      organization:{},
      periodStrategy: [],  //值列表：编制期段
      i18n: {}
    };
    this.validateStructureCode = debounce(this.validateStructureCode,1000)
  }

  componentWillMount(){
    //获取编制期段
    this.getSystemValueList(2002).then((response)=>{
      let periodStrategy = [];
      response.data.values.map((item)=>{
        let option = {
          id: item.code,
          value: item.messageKey
        };
        periodStrategy.push(option);
      });
      this.setState({
        periodStrategy: periodStrategy
      })
    });
    typeof this.props.organization.organizationName === "undefined" ?
      budgetService.getOrganizationById(this.props.params.id).then((response) =>{
        this.setState({
          organization: response.data,
        })
      })
      :
      this.setState({
        organization: this.props.organization,
      })
  }

  //新建预算表
  handleSave = (e) =>{
    const { structureName, description, i18n } = this.state;
    e.preventDefault();
    this.setState({
      loading: true,
    });

    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        values.organizationId = this.state.organization.id;
        budgetService.addStructure({ ...values, ...{ structureName, description, i18n } })
          .then((response) => {
            if (response) {
              message.success(messages('budget-setting.key31'/*保存成功！*/)); /*保存成功！*/
              response.data.organizationName = values.organizationName;
              this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key')
                .children
                .budgetStructureDetail
                .url
                .replace(':id', this.props.params.id)
                .replace(':structureId', response.data.id));
            }
          })
          .catch((e) => {
            if (e.response) {
              message.error(`${messages('common.save.filed')}, ${e.response.data.message}`);
            }
          })
          .finally(() => {
            this.setState({ loading: false });
          });
      }
    });
  };

  //点击取消，返回预算组织详情
  handleCancel = (e) =>{
    e.preventDefault();
    this.context.router.push(menuRoute.getMenuItemByAttr('budget-organization', 'key').children.budgetOrganizationDetail.url.replace(':id', this.props.params.id)+ '?tab=STRUCTURE');
  };

  validateStructureCode = (item,value,callback)=>{
    let params = {
      organizationId: this.props.params.id,
      structureCode: value
    };
    budgetService.getAllStructures(params).then((response)=>{
      let flag = false;
      if(response.data.length > 0 ){
        response.data.map((item)=>{
          if(item.structureCode === value) {
            flag = true;
          }
        })
      }
      flag >0 ? callback(messages('budget-setting.key200'/*该预算表已存在*/)) : callback();

    });
  };

  handleChange = ()=>{
    if(this.state.loading){
      this.setState({
        loading: false
      })
    }
  };


  handleI18n = (name, value, tag) => {
    let { i18n, structureName, description } = this.state;
    if (tag === 'input') {
      i18n.structureName = value;
      structureName = name;
    } else {
      i18n.description = value;
      description = name;
    }
    this.setState({ structureName, description, i18n });
  };


  render(){
    const { getFieldDecorator } = this.props.form;
    const { statusCode, organization, loading, periodStrategy, structureName, description, i18n } = this.state;

    const options = periodStrategy.map((item)=><Option key={item.id}>{item.value}</Option>)
    return(
      <div className="new-budget-structure">
        <div className="budget-structure-header">
          <Form onSubmit={this.handleSave} onChange={this.handleChange}>
            <Row gutter={24}>
              <Col span={8}>
                <FormItem
                  label={messages('budget-setting.key47'/*预算组织*/)}  /*{/!*预算组织*!/}*/
                  colon={true}>
                  {getFieldDecorator('organizationName', {
                    initialValue: organization.organizationName,
                    rules:[
                      { required:true }
                    ]
                  })(
                    <Input disabled/>)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={messages('budget-setting.key105'/*预算表代码*/)} /* {/!*预算表代码*!/}*/
                  colon={true}>
                  {getFieldDecorator('structureCode', {
                    rules:[
                      {required:true,message:messages('common.please.enter')},
                      {
                        validator:(item,value,callback)=>this.validateStructureCode(item,value,callback)
                      }
                    ]
                  })(
                    <Input placeholder={messages('common.please.enter')}
                    />)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={messages('budget-setting.key184'/*预算表名称*/)} /* {/!*预算表名称*!/}*/
                  colon={true}>
                  {getFieldDecorator('structureName', {
                    rules: [
                      { required: true, message: messages('common.please.enter') },
                    ]
                  })(
                    <LanguageInput
                      name={structureName}
                      i18nName={i18n.structureName || null}
                      nameChange={(name, structureName) => this.handleI18n(name, structureName, 'input')}
                      placeholder={messages('common.please.enter')/* 请输入 */}/>
                  )}
                </FormItem>
              </Col>
            </Row>
            <Row gutter={24}>
              <Col span={8}>
                <FormItem
                  label={messages('budget-setting.key185'/*编制期段*/)}  /*{/!*编制期段*!/}*/
                  colon={true}>
                  {getFieldDecorator('periodStrategy', {
                    rules:[
                      {required:true,message:messages('common.please.enter')},/* {/!*请输入*!/}*/
                    ],
                  })(
                    <Select placeholder={messages('common.please.select')}  /* {/!*请选择*!/}*/ getPopupContainer={triggerNode => triggerNode.parentNode}>
                      {options}
                    </Select>)
                  }
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={messages('budget-setting.key186'/*备注*/)} /* {/!*备注*!/}*/
                  colon={true}>
                  {getFieldDecorator('description')(
                    <LanguageInput
                      name={description}
                      i18nName={i18n.description || null}
                      nameChange={(name, description) => this.handleI18n(name, description, 'texArray')}
                      placeholder={messages('common.please.enter')/* 请输入 */}/>
                  )}
                </FormItem>
              </Col>
              <Col span={8}>
                <FormItem
                  label={messages('common.status',{status:statusCode})} /* {/!*状态*!/}*/
                  colon={false}>
                  {getFieldDecorator("isEnabled", {
                    initialValue: true,
                    valuePropName: 'checked',
                    rules:[
                      {
                        validator: (item,value,callback)=>{
                          this.setState({
                            statusCode: value ? messages('common.enabled') /*启用*/
                              : messages('common.disabled') /*禁用*/
                          })
                          callback();
                        }
                      }
                    ],
                  })
                  (<Switch checkedChildren={<Icon type="check" />} unCheckedChildren={<Icon type="cross"/>}/>)
                  }
                </FormItem>
              </Col>
            </Row>
            <Button type="primary" loading={loading} htmlType="submit">{messages('common.save') /*保存*/}</Button>
            <Button onClick={this.handleCancel} style={{ marginLeft: 8 }}> {messages('common.cancel') /*取消*/}</Button>
          </Form>
        </div>
      </div>
    )
  }
}

NewBudgetStructure.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization
  }
}



const WrappedNewBudgetStructure = Form.create()(NewBudgetStructure);

export default connect(mapStateToProps)(WrappedNewBudgetStructure);
